/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import Crawler.ClientHandler;
import DataStructures.Project;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URLDecoder;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

/**
 *
 * @author Manuel
 */
public class Input extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse resp) {
        
    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp) {
        try {
            int len = req.getContentLength();
            byte[] input = new byte[len];

            ServletInputStream sin = req.getInputStream();
            int c, count = 0 ;
            while ((c = sin.read(input, count, input.length-count)) != -1) {
                count +=c;
            }
            sin.close();

          String inString = new String(input);

           int index = inString.indexOf("=");
            if (index == -1) {
                System.out.println("RECEIVED WRONG REQUEST: "+inString);
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().print("Error reading from message.");
                resp.getWriter().close();
                return;
            }
            String value = URLDecoder.decode(inString.substring(index + 1),"UTF-8");

            //decode application/x-www-form-urlencoded string
            System.out.println("RECEIVED: "+value);

            //interpret and execute the String
            String response = this.interpretString(value);
            System.out.println("Responding "+response);

            // set the response code and write the response data
            resp.setStatus(HttpServletResponse.SC_OK);
            OutputStreamWriter writer = new OutputStreamWriter(resp.getOutputStream());

            writer.write(response);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            try{
                e.printStackTrace();
                System.out.println("EXCEPTION");
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().print(e.getMessage());
                resp.getWriter().close();
            } catch (IOException ioe) {
            }
        }

    }

    private String interpretString(String command) {
        System.out.println("RECEIVED "+command);
        ClientHandler handle = ClientHandler.getInstance();

        //request for links
        if(command.startsWith("0")){
            return handle.getNewLink();
        }

        //project data
        else if(command.startsWith("2")){
            String sub = command.substring(2);
            String code = sub.substring(0,sub.indexOf(";"));
            String xml = sub.substring(code.length()+1);
            Project project = this.unmarshallProject(xml);
            System.out.println("Unmarshalled");
            if(project == null)
                return "3;Failure. Could not interpret the data.";
            else
                return handle.storeProject(project, code);
        }

        //crawl request
        else if(command.startsWith("4")){
            String[] paras = command.split(";");
            if(paras.length < 3)
                return "5; Failure, you did not specify all parameters";
            return handle.crawlNewLinks(paras[1], paras[2]);
        }

         else
             return "Failure. Could not interpret request.";
    }

    private Project unmarshallProject(String xml){
        try {
            JAXBContext jc = JAXBContext.newInstance (Project.class);

            Unmarshaller u = jc.createUnmarshaller ();

           InputStream is = new ByteArrayInputStream(xml.getBytes());

           Project item = (Project) u.unmarshal (is);

        return item;

       } catch (JAXBException e) {
           e.printStackTrace ();
       }
        return null;

    }

}



